const log4j = require('./log4')
const dayjs = require('dayjs')
// 业务状态码
const CODE = {
  SUCCESS: 200, // 请求成功
  PARAM_ERROR: 10001, // 参数错误
  USER_ACCOUNT_ERROR: 20001, // 账号密码错误
  USER_LOGIN_ERROR: 30001, // 未登录
  BUSINESS_ERROR: 40001, // 业务请求失败
  AUTH_ERROR: 50001 // token失效
}
// 根据日期获取前一天
const getYesterday = (today) => {
  const today_ = new Date(today)
  const yesterday_ = new Date(today_.getTime() - 24 * 60 * 60 * 1000)
  const y = yesterday_.getFullYear()
  const m =
    yesterday_.getMonth() + 1 < 10
      ? '0' + (yesterday_.getMonth() + 1)
      : yesterday_.getMonth() + 1
  const d =
    yesterday_.getDate() < 10
      ? '0' + yesterday_.getDate()
      : yesterday_.getDate()
  const yesterday = y + '-' + m + '-' + d
  return yesterday
}

// 获取根据当前时间获取本周一
const getMonday = () => {
  let monday = ''
  const now = new Date()
  const nowTime = now.getTime()
  const day = now.getDay()
  const oneDayTime = 24 * 60 * 60 * 1000
  const MondayTime = nowTime - (day - 1) * oneDayTime
  monday = new Date(MondayTime)
  return dayjs(monday).format('YYYY-MM-DD')
}
// 根据当前时间获取本周日
const getSunday = () => {
  let sunday = ''
  const now = new Date()
  const nowTime = now.getTime()
  const day = now.getDay()
  const oneDayTime = 24 * 60 * 60 * 1000
  // 本周日时间戳
  const SundayTime = nowTime + (7 - day) * oneDayTime
  // 格式化时间
  sunday = new Date(SundayTime)
  return dayjs(sunday).format('YYYY-MM-DD')
}

// 获取本月第一天
const getMonthFirstday = () => {
  const date = new Date()
  date.setDate(1)
  return dayjs(date).format('YYYY-MM-DD')
}
// 获取本月最后一天

const getMonthLastday = () => {
  const date = new Date()
  const enddate = new Date(date.getFullYear(), date.getMonth() + 1, 0)
  return dayjs(enddate).format('YYYY-MM-DD')
}
module.exports = {
  getMonday,
  getSunday,
  getMonthFirstday,
  getMonthLastday,
  getYesterday,
  CODE,
  // 分页器
  pager: ({ pageNum, pageSize }) => {
    pageNum *= 1
    pageSize *= 1
    const skipIndex = (pageNum - 1) * pageSize
    return {
      page: {
        pageNum,
        pageSize
      },
      skipIndex
    }
  },
  // 请求成功
  success: (data, msg, code = CODE.SUCCESS) => {
    log4j.debug(data)
    return {
      data,
      msg,
      code
    }
  },
  // 请求失败
  fail: (msg, code = CODE.BUSINESS_ERROR, data) => {
    log4j.debug(msg)
    return {
      code,
      data,
      msg
    }
  }
}
